﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZilLion.Service.WeChatMall.Domain.Entitys.ShopInfo;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface.ShopInfo;

namespace ZilLion.Service.WeChatMall.Domain.Repositorys.ShopInfo
{
    public class ShopBasicInfoRepository : SqlServerRespository<ShopBasicInfoEntity>, IShopBasicInfoRepository
    {
        public ShopBasicInfoRepository()
        {
            Context = new WechatMallContext();
        }
        public IEnumerable<ShopBasicInfoEntity> GetShops(string zlcompanykey, string citycode = null)
        {
            var querysql = DapperHelper.CreateColSqlByMap<ShopBasicInfoEntity>();
            var condition = " WHERE zlcompanykey=@zlcompanykey ";
            if (citycode.IsNotNullOrEmpty())
                condition = condition + "shopadcode=@shopadcode";
            var result = GetList($"SELECT {querysql}  FROM shopbasicinfo {condition}",
                new {zlcompanykey, shopadcode = (citycode ?? string.Empty).ToLong()});
            return result;
        }

        public IEnumerable<ShopBasicInfoEntity> GetShopByAppId(string appid)
        {
            var querysql = DapperHelper.CreateColSqlByMap<ShopBasicInfoEntity>("a");
            var sql = $@"SELECT {querysql} FROM shopbasicinfo a
            INNER JOIN appshoprelationship b ON a.shopid=b.shopid
            WHERE b.appid=@appid";
            var result = GetList(sql, new {appid});
            return result;
        }

        public ShopBasicInfoEntity GetShopByid(long shopid)
        {
            var querysql = DapperHelper.CreateColSqlByMap<ShopBasicInfoEntity>();
            var result = GetList($"SELECT {querysql}  FROM shopbasicinfo where shopid=@shopid",
                new {shopid}).FirstOrDefault();
            return result;
        }

        public void AddInfo(ShopBasicInfoEntity entity, UnitOfWork unit = null)
        {
            Add(entity, unit);
        }

        public void RemoveInfo(ShopBasicInfoEntity entity, UnitOfWork unit = null)
        {
            Remove(entity, unit);
        }

        public void RemoveInfoByShopid(long shopid, UnitOfWork unit = null)
        {
            DapperHelper.Execute("DELETE FROM shopbasicinfo WHERE shopid=@shopid", Context, unit, new { shopid });
        }

        public void EditInfo(ShopBasicInfoEntity entity, UnitOfWork unit = null)
        {
            Modify(entity, unit);
        }
    }
}